package com.odobenus.client.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpTools {
	
	/** 
	 * 下载文件 
	 * @param url            http://www.xxx.com/img/333.jpg 
	 * @param destFileName   xxx.jpg/xxx.png/xxx.txt 
	 * @throws ClientProtocolException 
	 * @throws IOException 
	 */  
	public static void getFile(String url, String destFileName)  
	        throws ClientProtocolException, IOException {  
	    // 生成一个httpclient对象  
	    CloseableHttpClient httpclient = HttpClients.createDefault();  
	    HttpGet httpget = new HttpGet(url);  
	    HttpResponse response = httpclient.execute(httpget);  
	    HttpEntity entity = response.getEntity();  
	    InputStream in = entity.getContent();  
	    File file = new File(destFileName);  
	    try { 
	        FileOutputStream fout = new FileOutputStream(file);  
	        entity.writeTo(fout);
	        fout.flush();  
	        fout.close();  
	        System.out.println("fecth success,dest file path is "+destFileName);
	    } finally {  
	        // 关闭低层流。  
	        in.close();  
	    }  
	    httpclient.close();  
	}

	public static InputStream getFileInputStream(String url) {
		// 生成一个httpclient对象  
	    try {
			CloseableHttpClient httpclient = HttpClients.createDefault();  
			HttpGet httpget = new HttpGet(url);  
			HttpResponse response = httpclient.execute(httpget);  
			HttpEntity entity = response.getEntity();  
			InputStream in = entity.getContent();  
			return in;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;  
	} 
	
}
